package org.ibase4j.system.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ibase4j.jwt.utils.StringUtils;
import org.ibase4j.system.model.SysDic;
import org.ibase4j.system.model.SysRole;
import org.ibase4j.system.model.SysRoleMenu;
import org.ibase4j.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import top.ibase4j.core.base.BaseController;
import top.ibase4j.core.exception.BusinessException;
import top.ibase4j.core.exception.IllegalParameterException;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:15:43
 */
@RestController
@Api(value = "角色管理", description = "角色管理")
@RequestMapping(value = "role")
public class SysRoleController extends BaseController<SysRole, SysRoleService> {
    SysAuthorizeService authorizeService;
    SysCacheService sysCacheService;
    SysMenuService sysMenuService;
    @Autowired
    private SysDicService sysDicService;

    @ApiOperation(value = "获取角色菜单编号")
    @RequestMapping(value = "read/menu")
//    @RequiresPermissions("sys.base.role.setmenu")
    public Object getRoleMenu(ModelMap modelMap, @RequestBody SysRoleMenu param) {
        List<Long> menus = authorizeService.queryMenuIdsByRoleId(param.getRoleId());
        return setSuccessModelMap(modelMap, menus);
    }

    @ApiOperation(value = "修改角色菜单")
    @RequestMapping(value = "/update/menu")
//    @RequiresPermissions("sys.base.role.setmenu")
    public Object roleMenu(ModelMap modelMap, @RequestBody SysRoleMenu param) {
        Long roleId = param.getRoleId();
        if (roleId == null) throw new IllegalParameterException("参数错误.");
        Long currentUserId = getCurrUser().getId();
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        if(StringUtils.isNotEmpty(param.getIds())){
            List<Integer> menuIds = param.getIds();
            Set<Integer> mSubMenuIdsSet = menuIds.stream().collect(Collectors.toSet());
            for (Integer menuId : mSubMenuIdsSet) {
                if(menuId == null)continue;
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setPermission("read");
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId.longValue());
                sysRoleMenu.setCreateBy(currentUserId);
                sysRoleMenu.setUpdateBy(currentUserId);
                sysRoleMenu.setCreateTime(new Date());
                sysRoleMenu.setUpdateTime(new Date());
                sysRoleMenuList.add(sysRoleMenu);
            }
        }
        authorizeService.updateRoleMenu(sysRoleMenuList);
        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "获取角色操作权限")
    @RequestMapping(value = "read/permission")
//    @RequiresPermissions("sys.base.role.setperm")
    public Object queryRolePermissions(ModelMap modelMap, @RequestBody SysRoleMenu record) {
        List<Map<String, Object>> menuIds = authorizeService.queryRolePermissions(record);
        Set<Long> mRoldeSelectedIds = new HashSet<>();
        Map<String, List<SysDic>> allMenuBtnDicMap = sysDicService.getAllMenuBtnDic();
        for(Map<String, Object> oneMenu : menuIds){
            String btnDic = oneMenu.get("btnDic")+"";
            List<SysDic> dicList = allMenuBtnDicMap.get(btnDic);
            if(dicList == null){
                logger.info("这里菜单没有字典==>" + btnDic);
                continue;
            }
            for(SysDic dic : dicList){
                if(dic.getCode().equals(oneMenu.get("permission"))){
                    mRoldeSelectedIds.add(Long.parseLong((oneMenu.get("menuId") + dic.getParentCode())));
                    break;
                }
            }
        }
        return setSuccessModelMap(modelMap, mRoldeSelectedIds);
    }

    @ApiOperation(value = "修改角色操作权限")
    @RequestMapping(value = "/update/permission")
//    @RequiresPermissions("sys.base.role.setperm")
    public Object updateRolePermission(ModelMap modelMap, @RequestBody SysRoleMenu param) {
        Long roleId = param.getId();
        if (roleId != null  && roleId.longValue() != param.getId()) throw new IllegalParameterException("参数错误.");
        Long userId = getCurrUser().getId();
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        List<SysDic> allMenuBtnDicList = sysMenuService.queryMenuDicList();
        Map<String,String> allMenuBtnDicMap = new HashMap<>();
        for(SysDic dic : allMenuBtnDicList){
            allMenuBtnDicMap.put(dic.getParentCode(),dic.getCode());
        }

        if(StringUtils.isNotEmpty(param.getIds())){
            List<Integer> permIds = param.getIds();
            Set<Integer> mSubMenuIdsSet = permIds.stream().filter(item -> item+"".length() >= 6).collect(Collectors.toSet());
            for (Integer oneId : mSubMenuIdsSet) {
                String oneMenuId = oneId+"";
                if(oneMenuId.length() < 6)continue;
                String menuId =oneMenuId.substring(0,oneMenuId.length()- 5);
                String dicId = oneMenuId.substring(oneMenuId.length()- 5);
                String permition = allMenuBtnDicMap.get(dicId);
                if(StringUtils.isEmpty(permition))continue;
                if("read".equals(permition))continue;
//                int flag = oneMenuId.indexOf(JwtConstants.SEPRATER);
//                if(flag < 0)continue;
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(Long.parseLong(menuId));
                sysRoleMenu.setPermission(permition);
                sysRoleMenu.setCreateBy(userId);
                sysRoleMenu.setUpdateBy(userId);
                sysRoleMenu.setCreateTime(new Date());
                sysRoleMenu.setUpdateTime(new Date());
                sysRoleMenuList.add(sysRoleMenu);
            }
        }
        authorizeService.updateRolePermission(sysRoleMenuList);
        return setSuccessModelMap(modelMap);
    }


    //////////////////////////////////////////
    @ApiOperation(value = "查询角色")
    @RequiresPermissions("sys.base.role.read")
    @RequestMapping(value = "/read/dic")
    public Object dic(ModelMap modelMap, Map<String, Object> param) {
        return super.queryList(modelMap, param);
    }

    @Override
    @ApiOperation(value = "查询角色")
    @RequiresPermissions("sys.base.role.read")
    @PostMapping(value = "/read/page")
    public Object query(ModelMap modelMap, @RequestBody Map<String, Object> param) {
        return super.query(modelMap, param);
    }

    @ApiOperation(value = "查询角色")
    @RequiresPermissions("sys.base.role.read")
    @GetMapping(value = "/read/list")
    public Object list(ModelMap modelMap, @RequestBody Map<String, Object> param) {
        return super.queryList(modelMap, param);
    }

    @ApiOperation(value = "角色详情")
    @RequiresPermissions("sys.base.role.read")
    @GetMapping(value = "/read/detail")
    public Object get(ModelMap modelMap, @RequestBody SysRole param) {
        return super.get(modelMap, param);
    }

    @Override
    @PostMapping(value = "/save")
    @ApiOperation(value = "修改角色")
    @RequiresPermissions("sys.base.role.update")
    public Object update(ModelMap modelMap, @RequestBody SysRole param) {
        if (param.getId() != null) {
            SysRole result = service.queryById(param.getId());
            if ("3".equals(result.getRoleType())) {
                throw new BusinessException("不允许修改系统内置角色");
            }
        }
        return super.update(modelMap, param);
    }

    @Override
    @PostMapping(value = "/delete")
    @ApiOperation(value = "删除角色")
    @RequiresPermissions("sys.base.role.delete")
    public Object delete(ModelMap modelMap, @RequestBody SysRole param) {
        return super.delete(modelMap, param);
    }
}
